<template>
  <a-modal
    title="新增设备表"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          label="设备名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input placeholder="请输入设备名称" v-decorator="['deviceName', {rules: [{required: true, message: '请输入设备名称！'}]}]" />
        </a-form-item>

        <a-form-item
          label="设备类型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select
            :showSearch="true"
            optionFilterProp="children"
            style="width: 100%"
            placeholder="请选择设备类型"
            v-decorator="['productModel', {rules: [{ required: true, message: '请输入设备类型！' }]}]" >
            <a-select-option v-for="(item,index) in deviceList" :key="index" :value="item.code" >{{ item.value }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="产品厂商"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input placeholder="请输入产品厂商" v-decorator="['productVendor', {rules: [{required: true, message: '请输入产品厂商！'}]}]" />
        </a-form-item>

        <a-form-item
          label="所属站点"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          :hidden="true"
        >
          <a-select style="width: 100%" placeholder="请选择所属站点" v-decorator="['stationId', {rules: [{ required: true, message: '请选择所属站点！' }]}]" >
            <a-select-option v-for="(item,index) in stationTree" :key="index" :value="item.id" >{{ item.stationName }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="所属行业"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select style="width: 100%" placeholder="请选择所属行业" v-decorator="['industryId', {rules: [{ required: true, message: '请选择所属设备！' }]}]" >
            <a-select-option v-for="(item,index) in industryTypeList" :key="index" :value="item.id" >{{ item.industryType }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="投产日期"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-date-picker placeholder="请选择投产日期" @change="onChange" style="width: 100%" v-decorator="['createdAt']"></a-date-picker>
        </a-form-item>

        <a-form-item
          label="设备正面预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="fileName"
            :customRequest="customRequest"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="fileList"
            @change="change"
          >
            <img v-if="fileName" :src="fileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

        </a-form-item>
        <a-form-item
          label="设备反面预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="backFileName"
            :customRequest="customRequestback"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="backFileList"
            @change="changeback"
          >
            <img v-if="backFileName" :src="backFileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

        </a-form-item>
        <a-form-item
          label="设备铭牌预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="nameplateFileName"
            :customRequest="customRequestnameplate"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="nameplateFileList"
            @change="changenameplate"
          >
            <img v-if="nameplateFileName" :src="nameplateFileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>


        </a-form-item>
        <a-form-item
          label="首页标题预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="nameplateFileName"
            :customRequest="customRequestTitle"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="titleFileList"
            @change="changeTitle"
          >
            <img v-if="titleFileName" :src="titleFileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>

          <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { add } from '@/api/modular/main/bizdevice/bizDeviceManage'
  import { list } from '@/api/modular/main/bizstation/bizStationManage'
  import { industryTypeList } from '@/api/modular/main/bizindustryinvolved/bizIndustryInvolvedManage'
  import moment from 'moment'
  import { getUploadFileName, getUploadFileNameAndId, sysFileInfoUpload } from '@/api/modular/system/fileManage'
  import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'

  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        groupCodeList: {},
        form: this.$form.createForm(this),
        stationTree: [],
        treeLoading: true,
        birthdayString: [],
        industryTypeList: [],
        fileName: '',
        backFileName: '',
        nameplateFileName: '',
        titleFileId: '',
        titleFileName: '',
        fileList: [],
        backFileList: [],
        nameplateFileList: [],
        titleFileList: [],
        deviceList: [],
        previewVisible: false,
        previewImage: '',
        loading: false
      }
    },

    created () {
      this.getStationTree()
      this.getDeviceList()
      this.getIndustryTypeList()
    },

    methods: {
      add (record) {
        this.visible = true
        setTimeout(() => {
          this.form.setFieldsValue({
            stationId: record
          })
        }, 100)
      },
      getStationTree () {
        list().then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.stationTree = res.data
        })
      },
      getDeviceList () {
        sysDictTypeDropDown({ code: 'device_type' }).then((res) => {
          if (res.success) {
            this.deviceList = res.data
          }
        })
      },
      getIndustryTypeList () {
        industryTypeList().then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.industryTypeList = res.data
        })
      },
      /**
       * 上传文件
       */
      customRequest (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileName(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.fileName = res.data
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      /**
       * 上传文件
       */
      customRequestById (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.fileId = res.data
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      /**
       * 上传文件 customRequestback
       */
      customRequestback (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileName(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.backFileName = res.data
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      changeback ({ fileList }) {
        this.backFileList = fileList
      },
      // 上传文件
      customRequestnameplate (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileNameAndId(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.nameplateFileName = res.data.fileName
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      customRequestTitle (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileNameAndId(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.titleFileName = res.data.fileName
            this.titleFileId = res.data.fileId
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      changenameplate ({ fileList }) {
        this.nameplateFileList = fileList
      },
      changeTitle ({ fileList }) {
        this.titleFileList = fileList
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true

        validateFields((errors, values) => {
          if (!errors) {
            values.fileName = this.fileName
            values.backFileName = this.backFileName
            values.titleFileId = this.titleFileId
            // values.titleFileName = this.titleFileName
            values.nameplateFileName = this.nameplateFileName
            add(values).then((res) => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success('新增成功')
                this.handleCancel()
                this.$emit('ok', values)
              } else {
                this.$message.info('新增失败：' + res.message)
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      onChange (date, dateString) {
        if (date == null) {
          this.birthdayString = []
        } else {
          this.birthdayString = moment(date).format('YYYY-MM-DD')
        }
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.fileName = ''
        this.fileList = []
        this.backFileName = ''
        this.backFileList = []
        this.nameplateFileName = ''
        this.nameplateFileList = []
        this.titleFileList = []
      },
      getBase64 (file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => resolve(reader.result)
          reader.onerror = error => reject(error)
        })
      },
      previewCancel () {
        this.previewVisible = false
      },
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await this.getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      change ({ fileList }) {
        this.fileList = fileList
      }
    }
  }
</script>
